package com.ujson.chat.server.session;

import com.google.common.collect.Lists;
import com.ujson.base.common.utils.LogUtil;
import com.ujson.base.common.utils.StringUtil;
import com.ujson.chat.server.builder.MessageResponseBuilder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <h3>ujson-parent</h3>
 * <p>服务端会话, 关联user和channel</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-23 21:41
 */
@Slf4j
public class ServerSession {
    public static final AttributeKey<ServerSession> SESSION_KEY = AttributeKey.valueOf("SESSION_KEY");
    public static final Map<String, List<Channel>> USER_TO_CHANNEL_MAP = new ConcurrentHashMap<>();
    public static final Map<Channel, String> CHANNEL_TO_USER_MAP = new ConcurrentHashMap<>();

    private static class ServerSessionHolder {
        private static final ServerSession INSTANCE = new ServerSession();
    }
    public static ServerSession inst() {
        return ServerSessionHolder.INSTANCE;
    }

    public ServerSession bind(ChannelHandlerContext ctx, String username) {
        Channel channel = ctx.channel();
        channel.attr(SESSION_KEY).set(this);
        USER_TO_CHANNEL_MAP.computeIfAbsent(username, k -> Lists.newLinkedList()).add(channel);
        CHANNEL_TO_USER_MAP.put(channel, username);
        return this;
    }

    public ServerSession remove(Channel channel) {
        String username = CHANNEL_TO_USER_MAP.get(channel);
        if (StringUtils.isNotBlank(username)) {
            USER_TO_CHANNEL_MAP.remove(username);
        }
        CHANNEL_TO_USER_MAP.remove(channel);
        channel.close();
        return this;
    }


}
